/*
 * Created on 2005-10-17
 *
 */
package com.yl.cap.analyst.work.actions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Category;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.faquir.hibernate.queryhelper.Page;
import org.faquir.license.License;
import org.faquir.license.LicenseFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yl.cap.analyst.work.service.WorkService;

public class WorkAction extends DispatchAction
{
    Category log = Logger.getLogger("work");
    private WorkService getService()
    {
        ApplicationContext ctx = WebApplicationContextUtils
                .getWebApplicationContext(this.getServlet().getServletContext());
        return (WorkService) ctx.getBean("workService");
    }

    public final ActionForward searchTask(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        List tasks = null;
        boolean res = false;

        try
        {
            String groupId = (String) request.getSession()
                    .getAttribute("group");
            WorkService service = getService();
            tasks = service.searchTask(groupId);
        }
        catch (Exception e)
        {
            log.error("searchTask error: " + e);
            errors.add("searchTask", new ActionError("errors.UnKnowError"));
            e.printStackTrace();
        }
        try
        {
            License license = LicenseFactory.getLicense();
            ServletContext application = this.getServlet().getServletContext();

            res = license.canUse(new File(application
                    .getRealPath("/conf/license/" + "license")));

        }
        catch (Exception e)
        {
            log.fatal("License Error",e);
            res = false;
        }
        if (!res)
        {
            log.fatal("License Error");
            errors.add("User login", new ActionError("errors.LicenseError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }
        else
        {
            request.setAttribute("tasks", tasks);
            return (mapping.findForward("tasklist"));
        }
    }

    public final ActionForward addTask(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String taskFileName = request.getParameter("taskName");

        try
        {
            WorkService service = getService();
            service.addTask(taskFileName);
        }
        catch (Exception e)
        {
            log.error("addTask error: " + e);
            errors.add("addTask", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }
        else
        {
            return (mapping.findForward("success"));
        }
    }

    public final ActionForward getAllTrigger(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        List triggers = null;
        List tasks = null;
        Boolean state = null;
        boolean res = false;
        try
        {
            License license = LicenseFactory.getLicense();
            ServletContext application = this.getServlet().getServletContext();

            res = license.canUse(new File(application
                    .getRealPath("/conf/license/" + "license")));

        }
        catch (Exception e)
        {
            log.fatal("License Error",e);
            res = false;
        }
        if (!res)
        {
            log.fatal("License Error");
            errors.add("User login", new ActionError("errors.LicenseError"));
        }
        try
        {
            WorkService service = getService();
            triggers = service.getAllTrigger();
            if (triggers != null && triggers.size() > 0)
            {
                tasks = service.getTaskByTiger((String) triggers.get(0));
            }
            state = (Boolean)service.getTriggerState().get(0);
        }
        catch (Exception e)
        {
            res = false;
            log.error("getAllTrigger error: " + e);
            errors.add("getAllTrigger", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        request.setAttribute("tasks", tasks);
        request.setAttribute("triggers", triggers);
        request.setAttribute("state", state);
        return (mapping.findForward("listTriggers"));
    }

    public final ActionForward getTaskByTrigger(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String triggerName = request.getParameter("triggerName");
        List triggers = null;
        List tasks = null;
        Boolean state = null;

        try
        {
            WorkService service = getService();
            triggers = service.getAllTrigger();
            tasks = service.getTaskByTiger(triggerName);
            state = service.getTriggerState(triggerName);
        }
        catch (Exception e)
        {
            log.error("getTaskByTrigger error: " + e);
            errors.add("getTaskByTrigger",
                    new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        request.setAttribute("tasks", tasks);
        request.setAttribute("triggers", triggers);
        request.setAttribute("triggerName", triggerName);
        request.setAttribute("state", state);
        return (mapping.findForward("listTriggers"));
    }

    public final ActionForward delTask(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String triggerName = request.getParameter("triggerName");
        String taskFileName = request.getParameter("taskName");

        try
        {
            WorkService service = getService();
            service.delTask(triggerName, taskFileName);
        }
        catch (Exception e)
        {
            log.error("delTask error: " + e);
            errors.add("delTask", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        return (mapping.findForward("success"));
    }

    public final ActionForward changeJobState(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String triggerName = request.getParameter("triggerName");
        String state = request.getParameter("state");

        try
        {
            WorkService service = getService();
            if ("0".equals(state))
            {
                service.disableTrigger(triggerName);
            }
            else if ("1".equals(state))
            {
                service.enableTrigger(triggerName);
            }
        }
        catch (Exception e)
        {
            log.error("changeJobState error: " + e);
            errors.add("changeJobState", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        return (mapping.findForward("success"));
    }

    public final ActionForward reOrderTask(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String newOrder = request.getParameter("hidTaskOrder");
        String trigger = request.getParameter("triggerName");
        StringTokenizer orderTok = new StringTokenizer(newOrder, ";");
        List newOrderList = new ArrayList();
        while (orderTok.hasMoreTokens())
        {
            newOrderList.add(orderTok.nextToken());
        }

        try
        {
            WorkService service = getService();
            service.reOrderTask(trigger, newOrderList);
        }
        catch (Exception e)
        {
            log.error("reOrderTask error: " + e);
            errors.add("reOrderTask", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        return (mapping.findForward("success"));
    }

    public final ActionForward execJob(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        String trigger = request.getParameter("triggerName");
        boolean res = false;
        try
        {
            License license = LicenseFactory.getLicense();
            ServletContext application = this.getServlet().getServletContext();

            res = license.canUse(new File(application
                    .getRealPath("/conf/license/" + "license")));

        }
        catch (Exception e)
        {
            log.fatal("License Error",e);
            res = false;
        }
        if (!res)
        {
            log.fatal("License Error");
            errors.add("User login", new ActionError("errors.LicenseError"));
        }
        try
        {
            WorkService service = getService();
            service.executeJob(trigger);
        }
        catch (Exception e)
        {
            log.error("execJob error: " + e);
            errors.add("execJob", new ActionError("errors.UnKnowError"));            
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        return (mapping.findForward("success"));
    }

    public final ActionForward getAllJobLog(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        List logs = null;

        try
        {
            WorkService service = getService();
            logs = service.getAllJobName();
        }
        catch (Exception e)
        {
            log.error("getAllJobLog error: " + e);
            errors.add("getAllJobLog", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        request.setAttribute("logs", logs);
        return (mapping.findForward("listJobLog"));
    }

    public final ActionForward getTask(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        List tasks = null;
        String jobId = request.getParameter("jobId");

        try
        {
            WorkService service = getService();
            tasks = service.getTaskByJob(jobId);
        }
        catch (Exception e)
        {
            log.error("getTask error: " + e);
            errors.add("getTask", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        request.setAttribute("tasks", tasks);
        return (mapping.findForward("listTaskLog"));
    }

    public final ActionForward getJobLog(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        Page page = null;
        String logName = request.getParameter("jobName");
        String strFrom = request.getParameter("from");
        String strTo = request.getParameter("to");
        String strCp = request.getParameter("current") == null ? "1" : request
                .getParameter("current");
        int cp = Integer.parseInt(strCp);
        List logNames = null;

        try
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date from = sdf.parse(strFrom);
            Date to = sdf.parse(strTo);
            WorkService service = getService();
            page = service.getJob(logName, from, to, cp);
            logNames = service.getAllJobName();
        }
        catch (Exception e)
        {
            log.error("getJobLog error: " + e);
            errors.add("getJobLog", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        request.setAttribute("page", page);
        request.setAttribute("logs", logNames);
        request.setAttribute("cp", new Integer(cp));
        return (mapping.findForward("listJobLog"));
    }

    public final ActionForward getLastLog(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException
    {
        ActionErrors errors = new ActionErrors();
        Page page = null;
        String strCp = request.getParameter("current") == null ? "1" : request
                .getParameter("current");
        int cp = Integer.parseInt(strCp);
        List logNames = null;

        try
        {
            WorkService service = getService();
            page = service.getLastLog(cp);
            logNames = service.getAllJobName();
        }
        catch (Exception e)
        {
            log.error("getLastLog error: " + e);
            errors.add("getLastLog", new ActionError("errors.UnKnowError"));
        }

        if (!errors.isEmpty())
        {
            saveErrors(request, errors);
            return mapping.findForward("faile");
        }

        request.setAttribute("page", page);
        request.setAttribute("logs", logNames);
        request.setAttribute("cp", new Integer(cp));
        return (mapping.findForward("listLastLog"));
    }
}
